package com.ning.farm_income_back.service;

import com.ning.farm_income_back.domain.Distributionrules;
import com.ning.farm_income_back.domain.Profitpools;
import com.ning.farm_income_back.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ProfitService {

    @Autowired
    private ProfitpoolsMapper profitpoolsMapper;

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private CostsMapper costsMapper;

    @Autowired
    private RevenueMapper revenueMapper;

    @Autowired
    private DistributionrulesMapper distributionrulesMapper;

    @Autowired
    private UserrevenueaccountsMapper userrevenueaccountsMapper;
    @Autowired
    private DistributionrecordsMapper distributionrecordsMapper;

    public String getTotalProfit() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        String year = format.format(new Date());
        return profitpoolsMapper.selectByYear(year);
    }

    public String getOneProfit(String username) {
        Integer userId = usersMapper.selectByUsername(username).getUserId();
        return userrevenueaccountsMapper.selectByUserId(userId);
    }


    public void updateProfit() {
        //新建利润池
        Profitpools p =  new Profitpools();
        //获取当前年
        Calendar cal = Calendar.getInstance();
        String year = Integer.toString(cal.get(Calendar.YEAR));
        //获取当前年总利润
        String allCost = costsMapper.selectTotalByYear(year);
        if(allCost == null) {
            allCost = "0";
        }
        String allRevenue = revenueMapper.selectTotalByYear(year);
        if(allRevenue == null) {
            allRevenue = "0";
        }
        double TotalProfit = Double.parseDouble(allRevenue) - Double.parseDouble(allCost);
        Integer poolId = profitpoolsMapper.selectIdByYear(year);
        if(poolId == null) {
            p.setSeasonYear(year);
            p.setCreatedBy(1);
            p.setTotalProfit(new BigDecimal(0));
            p.setReservedAmount(new BigDecimal(0));
            p.setCreatedAt(new Date());
            profitpoolsMapper.insert(p);
        }else{
            p = profitpoolsMapper.selectByPrimaryKey(poolId.longValue());
        }
        //获取分配规则
        Distributionrules rule =  distributionrulesMapper.selectByPrimaryKey(1L);
        double reserved = TotalProfit * rule.getReserve()/100.00;
        double distribute = TotalProfit * rule.getDividend()/100.00;

        p.setTotalProfit(new BigDecimal(TotalProfit));
        p.setReservedAmount(new BigDecimal(reserved));
        p.setDistributedAmount(new BigDecimal(distribute));

        profitpoolsMapper.updateByPrimaryKey(p);
    }
}
